﻿using System;
using System.Collections.Generic;
using System.Net;

namespace Toybox.NicoSharp.Live
{
	using Utilities;

	partial class LiveMessageClient
	{
		/// <summary>
		/// コメント送信用キー クラス
		/// </summary>
		public class PostKey : Toybox.NicoSharp.Abstracts.AbstractKey
		{

			#region Constructor

			/// <summary>
			/// Constructor
			/// </summary>
			/// <param name="thread"></param>
			/// <param name="cookies"></param>
			public PostKey(string thread, CookieCollection cookies)
				: base(thread, cookies)
			{
			}

			#endregion Constructor


			#region Public Members

			/// <summary>
			/// コメントブロックNo (コメント数 / 100)
			/// </summary>
			public int BlockNo
			{
				get { return _blockNo; }
				protected set
				{
					if (_blockNo == value)
						return;

					_blockNo = value;

					OnPropertyChanged("BlockNo");
				}
			}
			private int _blockNo;

			#endregion Public Members


			#region Public Methods

			/// <summary>
			/// キーの更新
			/// </summary>
			/// <param name="block_no"></param>
			/// <returns></returns>
			public string Update(int block_no = -1)
			{
				return base.Update(CreateUrl(block_no));
			}

			/// <summary>
			/// キーの更新 (非同期)
			/// </summary>
			/// <param name="block_no"></param>
			public void UpdateAsync(int block_no = -1)
			{
				base.UpdateAsync(CreateUrl(block_no));
			}

			#endregion Public Methods

			#region Protected Methods

			/// <summary>
			/// 更新用URL作成
			/// </summary>
			/// <param name="block_no"></param>
			/// <returns></returns>
			protected virtual string CreateUrl(int block_no)
			{
				if (0 <= block_no)
					this.BlockNo = block_no;

				Dictionary<string, string> dict = new Dictionary<string, string>();
				dict.Add("thread", this.Thread);
				dict.Add("block_no", this.BlockNo.ToString());

				return NicoUrls.LiveApi + "getpostkey?" + Serializer.AndEqualPairSerializer(dict);
			}

			#endregion Protected Methods

			#region Override Methods

			/// <summary>
			/// Keyのセット
			/// </summary>
			/// <param name="text"></param>
			protected override void SetKey(string text)
			{
				Value = text.Split('=')[1];
				string[] values = Value.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
				Expires = int.Parse(values[0]);
			}

			#endregion Override Methods

		}
	}
}